package top.bluesword.laboratory.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.modelcontextprotocol.json.jackson.JacksonMcpJsonMapper;
import io.modelcontextprotocol.server.McpAsyncServer;
import io.modelcontextprotocol.server.McpServer;
import io.modelcontextprotocol.server.McpServerFeatures;
import io.modelcontextprotocol.server.transport.WebMvcSseServerTransportProvider;
import io.modelcontextprotocol.spec.McpSchema;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.function.RouterFunction;
import org.springframework.web.servlet.function.ServerResponse;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.Map;

/**
 * <a href="https://modelcontextprotocol.io/sdk/java/mcp-server">MCP Java Sdk 文档</a>
 */
@Configuration
class McpConfig {

    @Bean
    WebMvcSseServerTransportProvider webMvcSseServerTransportProvider(ObjectMapper mapper) {
        return
            WebMvcSseServerTransportProvider
                .builder()
                .jsonMapper(new JacksonMcpJsonMapper(mapper))
                .messageEndpoint("/mcp/message")
                .build();
    }

    @Bean
    RouterFunction<ServerResponse> mcpRouterFunction(WebMvcSseServerTransportProvider transportProvider) {
        return transportProvider.getRouterFunction();
    }

    @Bean
    McpAsyncServer mcpServer(WebMvcSseServerTransportProvider webMvcSseServerTransportProvider) {
        McpAsyncServer mcpAsyncServer = McpServer.async(webMvcSseServerTransportProvider)
            .serverInfo("my-server", "1.0.0")
            .capabilities(McpSchema.ServerCapabilities.builder()
                .resources(true, true)
                .tools(true)
                .prompts(true)
                .logging()
                .build())
            .build();
        McpSchema.JsonSchema schema = new McpSchema.JsonSchema("object", Map.of(), List.of(), false,Map.of(),Map.of());
        McpServerFeatures.AsyncToolSpecification toolSpecification =
            new McpServerFeatures.AsyncToolSpecification(
                McpSchema.Tool.builder().name("说你好").description("说你好").inputSchema(schema).build(),
                null,
                (exchange, request) ->
                    Mono.just(McpSchema.CallToolResult.builder().addContent(new McpSchema.TextContent("你好")).build())
            );
        mcpAsyncServer.addTool(toolSpecification).subscribe();
        return mcpAsyncServer;
    }

}